from bson import ObjectId
from fastapi import APIRouter, Query

from components.router import CenterRoute
from config import col_activity, col_activity_institution, col_institution
from controller.crud_es_query import crud_alumni_by_id, crud_get_alunmi_by_institution_id, \
    crud_get_act_by_institution_id, crud_person_activation_list
from ioservice.alumni.alumni import get_alumni_by_id, aggregate_alumni, search_alumni
from controller.alumni import parse_alumni_search_results, get_alumni_extra_data, \
    parse_alumni_agg_results, get_recent_active_alumni

from models.alumni import *
from models.alumni_extra import AlumniExtraDataSearchModel
from task_utils.task_institution_overview import institution_query

router = APIRouter(route_class=CenterRoute)


@router.get("/alumni/{alumni_id}")
async def api_get_alumni_info(alumni_id: OID):
    res = await get_alumni_by_id(alumni_id)
    return res


@router.post('/alumni/search', response_model_exclude_unset=True)
async def api_search_alumni(context: AlumniSearchModel):
    total, results = await search_alumni(context)
    await parse_alumni_search_results(results, context)
    aggregation = await aggregate_alumni(context)
    aggregation = await parse_alumni_agg_results(aggregation)
    return {"items": results, "total": total, "aggregation": aggregation}


@router.post('/alumni/{alumni_id}/extra', response_model_exclude_unset=True)
async def api_search_alumni_extra_info(alumni_id: OID, context: AlumniExtraDataSearchModel):
    res = await get_alumni_extra_data(alumni_id, context)
    return res


@router.get("/alumni/active/alumni")
async def api_get_active_alumni():
    """
    活跃人才
    """
    return await get_recent_active_alumni()


@router.get("/desk/alumni/{alumni_id}")
async def api_get_alumni_info(alumni_id: str):
    res = await crud_alumni_by_id(alumni_id)
    return res


@router.get("/desk/alumni/activation/{alumni_id}")
async def api_get_alumni_info(alumni_id: str, page: int = 1, size: int = 10):
    res = await crud_person_activation_list(alumni_id, page, size)
    return res


@router.get("/desk/institutions/{institution_id}/alumni", description="机构详情::联系人才列表")
async def get_inst_with_alumni(
        institution_id: str,

        page: int = Query(alias='pageNum', default=1),
        size: int = Query(default=10, alias="pageSize"),
):

    res = await crud_get_alunmi_by_institution_id(institution_id, page, size)
    return res


@router.get("/desk/institutions/{institution_id}/activity", description="机构详情::组织活动列表")
async def get_inst_with_activity(
        institution_id: str,
        page: int = Query(alias='pageNum', default=1),
        size: int = Query(default=10, alias="pageSize"),
):
    res = await crud_get_act_by_institution_id(institution_id, page, size)
    return res


@router.get("/desk/institutions/{institution_id}/institution", description="机构详情::赋能组织列表")
async def get_inst_with_institution(
        institution_id: str,
        page: int = Query(alias='pageNum', default=1),
        size: int = Query(default=10, alias="pageSize"),
):
    query = institution_query(inst_id=institution_id)
    query["is_deleted"] = {"$ne": True}

    act_ids = col_activity.find(query).distinct("_id")

    contact_institution_docs = col_activity_institution.find(
        {"activity_id": {"$in": act_ids}, "is_attended": True}, {"institution_id": 1, "_id": 0}
    )

    contact_institution_ids = [p.get("institution_id") for p in contact_institution_docs]

    # 分页获取机构数据
    total = len(set(contact_institution_ids))

    contact_institution_ids = list(set(contact_institution_ids))

    if contact_institution_ids:
        institutions = col_institution.find({"_id": {"$in": contact_institution_ids}}).sort("oindex").skip(
            (page - 1) * size).limit(size)
        data = []
        for inst in institutions:
            item = {"id": str(inst["_id"]), "institution_name": inst['institution_name'],
                    "is_kexie": inst.get("in_kexie", False), "acc_alumni": inst.get("acc_alumni", 0),
                    "institution_type": inst.get("institution_type", ""),
                    "acc_activity": col_activity_institution.count_documents({"institution_id": inst["_id"]})}

            data.append(
                item
            )
    else:
        data = []
    return {"total": total, "data": data}


@router.get("/desk/activity/{activity_id}/institution", description="机构详情::赋能组织列表")
async def get_inst_with_institution(
        activity_id: str,
        page: int = Query(alias='pageNum', default=1),
        size: int = Query(default=10, alias="pageSize"),
):
    activity_id = ObjectId(activity_id)
    contact_institution_docs = col_activity_institution.find(
        {"activity_id": {"$in": [activity_id]}, "is_attended": True}, {"institution_id": 1, "_id": 0}
    )

    contact_institution_ids = [p.get("institution_id") for p in contact_institution_docs]

    # 分页获取机构数据
    total = len(set(contact_institution_ids))

    contact_institution_ids = list(set(contact_institution_ids))

    if contact_institution_ids:
        institutions = col_institution.find({"_id": {"$in": contact_institution_ids}}).sort("oindex").skip(
            (page - 1) * size).limit(size)
        data = []
        for inst in institutions:
            item = {"id": str(inst["_id"]), "institution_name": inst['institution_name'],
                    "is_kexie": inst.get("in_kexie", False), "acc_alumni": inst.get("acc_alumni", 0),
                    "institution_type": inst.get("institution_type", ""),
                    "acc_activity": col_activity_institution.count_documents({"institution_id": inst["_id"]})}

            data.append(
                item
            )
    else:
        data = []
    return {"total": total, "data": data}